/* model */
import { ConnectorConditionTypeEnum, ConnectorFieldEnNameEnum, ConnectorFromField, ConnectorOptionsOperate, ConnectorToField } from '@src/modules/connector/model'
/* util */
import { uuid } from 'pub-bbx-utils'
import { connectorToField2FormField } from '@src/modules/connector/util/form'
import { initialize } from '@src/component/form/util'
import { isFalsy } from '@src/util/type'
/* types */
import { ConnectorRuleFormItemType } from '@src/modules/connector/types'

function getConnectorRuleFormItemDefaultCondition(toField?: ConnectorToField): ConnectorConditionTypeEnum {
  
  // 无对应字段, 默认为固定值
  if (isFalsy(toField)) {
    return ConnectorConditionTypeEnum.FixedValue
  }
  
  const enName = toField?.enName || ''
  
  // tags 部门，暂时只有固定值
  if (enName === ConnectorFieldEnNameEnum.Tags) {
    return ConnectorConditionTypeEnum.FixedValue
  }
  
  // 其他默认为对应方式
  return ConnectorConditionTypeEnum.FromField
}

/**
 * @description 创建规则表单项
*/
function createConnectorRuleFormItem(toField?: ConnectorToField): ConnectorRuleFormItemType {  

  
  
  const enName = toField?.enName || ''
  const leftFieldValue = enName
  
  const condition = getConnectorRuleFormItemDefaultCondition(toField)
  
  const formField = connectorToField2FormField(toField)
  const result = initialize([formField])
  const value = result[formField.fieldName]
  const required = toField?.required || false

  const parentEnName = toField?.parentEnName || ''
  
  return {
    id: uuid(),
    field: null,
    value,
    componentName: '',
    bind: {},
    operator: '',
    operators: [],
    condition,
    leftFieldValue,
    rightFieldValue: '',
    required,
    parentEnName,
  }
}

function getRuleGroupFromFieldDisplayItem(item: ConnectorRuleFormItemType, fromFieldList: ConnectorFromField[]) {
  
  // 对应字段值
  const rightFieldValue = item?.rightFieldValue || ''
  // 是否有子属性
  const isHaveChild = rightFieldValue.includes('.')
  
  if (isHaveChild) {
    
    const [fieldName, childFieldName] = rightFieldValue.split('.')
    
    const fieldItem = fromFieldList.find(item => item.enName === fieldName)
    const childItem = fieldItem?.children?.find(item => item.enName === childFieldName)
    
    const childFieldNameDisplay = childItem?.cnName || ''
    const fieldNameDisplay = fieldItem?.cnName || ''
    
    const cnName = `${fieldNameDisplay}/${childFieldNameDisplay}`
    
    item.rightField = {
      cnName: cnName
    }
    
    return
    
  }
  
  fromFieldList.forEach(fromField => {
    if (fromField.enName === rightFieldValue) {
      item.rightField = fromField
    }
  })
  
}

export {
  createConnectorRuleFormItem,
  getRuleGroupFromFieldDisplayItem
}
